// 获取应用实例
const app = getApp();

Page({
  data: {
    userInfo: null,
    studyDays: 0,
    statistics: {
      totalQuestions: 0,
      correctRate: 0,
      totalTime: 0
    }
  },

  onLoad() {
    // 检查登录状态
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo
      });
      this.loadPageData();
    }
  },

  onShow() {
    if (app.globalData.userInfo) {
      this.loadPageData();
    }
  },

  // 加载页面数据
  loadPageData() {
    this.getStudyStatistics();
  },

  // 获取学习统计
  getStudyStatistics() {
    app.showLoading();
    app.request({
      url: '/users/statistics',
      method: 'GET'
    }).then(res => {
      app.hideLoading();
      if (res.code === 0) {
        this.setData({
          studyDays: res.data.studyDays,
          statistics: {
            totalQuestions: res.data.totalQuestions,
            correctRate: res.data.correctRate,
            totalTime: (res.data.totalTime / 60).toFixed(1) // 转换为小时
          }
        });
      }
    }).catch(() => {
      app.hideLoading();
      app.showError('获取统计数据失败');
    });
  },

  // 页面跳转方法
  goToLogin() {
    wx.navigateTo({
      url: '/pages/login/login'
    });
  },

  editProfile() {
    wx.navigateTo({
      url: '/pages/profile/edit/edit'
    });
  },

  goToStudyHistory() {
    wx.navigateTo({
      url: '/pages/profile/study-history/study-history'
    });
  },

  goToFavorites() {
    wx.navigateTo({
      url: '/pages/profile/favorites/favorites'
    });
  },

  goToNotes() {
    wx.navigateTo({
      url: '/pages/profile/notes/notes'
    });
  },

  goToSettings() {
    wx.navigateTo({
      url: '/pages/profile/settings/settings'
    });
  },

  goToHelp() {
    wx.navigateTo({
      url: '/pages/profile/help/help'
    });
  },

  goToAbout() {
    wx.navigateTo({
      url: '/pages/profile/about/about'
    });
  },

  // 退出登录
  logout() {
    wx.showModal({
      title: '提示',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          app.clearToken();
          this.setData({
            userInfo: null,
            studyDays: 0,
            statistics: {
              totalQuestions: 0,
              correctRate: 0,
              totalTime: 0
            }
          });
        }
      }
    });
  }
}); 